<template>
  <DFModal
    ref="dfModal"
    class="adjustmentOrder-modal basicModal"
    :width="800"
    @register="modalRegister"
    @on-ok="okModalFn"
  >
    <template #default>
      <DFTable
        ref="dfTable"
        :columns="tableColumns"
        :row-key="(row) => row.orderCode"
        :pagination="false"
        :checked-row-key-model="true"
      />
    </template>
  </DFModal>
</template>

<script lang="ts" setup>
  import { DFModal, useModal } from '@/components/DFModal'

  import { DFTable } from '@/components/DFTable'

  import { useMixins } from '@/hooks/useMixins'

  import { renderSvg } from '@/utils/index'
  import { updateProOrder } from '@render/api/production/order'

  import Sortable from 'sortablejs'

  interface Props {
    orderList: any
  }

  const emit = defineEmits([
    'loadOrderFn',
    'register'
  ])

  const props = withDefaults(defineProps<Props>(), {
    orderList: () => [],
  })

  const [modalRegister, { openModal, closeModal, setSubLoading }] = useModal({})

  const { message, t } = useMixins()

  const tableColumns = [
    {
      label: 'orderCode',
      key:'orderCode',
      width: 220,
    },
    {
      label: 'customerOrderNo',
      key: 'customerOrderNo',
      width: 220,
    },
    {
      label: 'erpNo',
      key:'erpNo',
      width: 220,
    },
    {
      label: 'materialCode',
      key:'materialCode',
      width: 220,
    },
    {
      label: 'materialName',
      key:'materialName',
      width: 220,
    },
    {
      label: 'version',
      key:'version',
      width: 220,
    },
    {
      label: 'sort',
      common: true,
      sorter: false,
      align: 'center',
      fixed: 'right',
      className: 'sort-column',
      // title() {
      //   return h('div', {
      //     class: '123123123',
      //     width: '100%',
      //     'text-align': 'center',
      //     innerText: t(`common.table.sort`),
      //   });
      // },
      render(_row) {
        return h(renderSvg('fixedModalSort'), { class: 'fixed-modal-sort' })
      },
    },
  ]

  const list:any = ref([]);

  const dfTable = ref(null);

  async function openModalFn() {
    list.value = props.orderList.map((item,key)=>({...item,index:key+1}));

    openModal(null, t('productionCenter.table.adjustmentOrder'))

    nextTick(() => {
      dfTable.value && dfTable.value.setTableData(list.value)

      nextTick(() => {
        // 需要支持拖动效果的列表容器，在这里我们设置为el-table组件的tbody，
        // 注意：最前面的一段为前面el-table的class: draggable-table，主要为了防止如果页面有多个table，多个table同时实现拖拽效果
        // 当然，如果多个table都需要拖拽效果，选择器中最前面的.draggable-table可以去除。
        const tbody = document.querySelector('.adjustmentOrder-modal .n-data-table-tbody')

        new Sortable(tbody, {
          animation: 150,
          handle: '.fixed-modal-sort',
          filter: '.no-draggable',
          invertSwap: false,
          preventOnFilter: true,
          onSort(/** Event */ _evt) {
            // console.log('sort',evt)
            // 与 onEnd 相同的属性
          },
          onChange(_e, _a, _c) {
            // console.log('change',e)
            // console.log(a)
            // if(e.newIndex === 2){
            //   return false
            // }
          },
          onMove(/** Event */ _evt, /** Event */ _originalEvent) {
            // console.log('move',evt)
            // console.log(originalEvent)
            // if(evt.newIndex === 2){
            //   return false
            // }
            // return false
          },
          // 需要在odEnd方法中处理原始eltable数据，使原始数据与显示数据保持顺序一致
          onEnd: ({ newIndex, oldIndex }) => {
            // console.log(newIndex)

            // console.log(oldIndex)

            const targetRow = list.value[oldIndex]
            list.value.splice(oldIndex, 1)
            list.value.splice(newIndex, 0, targetRow)

            list.value.forEach((item, key) => {
              item.index = key + 1
            })

            // console.table(this.dialogTableDataList);
          },
        })
      })

      // console.log(dfTable.value);
    })
  }

  async function okModalFn() {
    try {
      // modalSubmitFn()

      const dataList = unref(list).map((item, key) => ({ ...item, proOrder: key }));

      await updateProOrder(dataList);

      message.success(t('common.tipMsg.isSucc'));

      emit('loadOrderFn');

      closeModal();
    }
    catch (e) {
      console.log(e)
    }

    nextTick(() => {
      setSubLoading(false);
    })
  }

  defineExpose({
    openModalFn,
  })
</script>

<style lang="less">
  .adjustmentOrder-modal {
    .fixed-modal-sort {
      width: 18px;
      height: 18px;
      margin: 0 auto;
      cursor: move;
    }
  }
  .sort-column > .n-data-table-th__title-wrapper {
    justify-content: space-around;
  }
</style>
